package net.csdn.business.common.feign.decoder;

import feign.FeignException;
import feign.Response;
import net.csdn.business.common.domain.ResponseResult;
import net.csdn.business.common.enums.ResultCodeEnum;
import net.csdn.business.common.exception.BusinessException;
import net.csdn.business.common.utils.JsonUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author likun
 * @date 2022/12/29 13:26
 */
public class SysCustomDecoder extends SpringDecoder {
    public SysCustomDecoder(ObjectFactory<HttpMessageConverters> messageConverters, ObjectProvider<HttpMessageConverterCustomizer> customizers) {
        super(messageConverters, customizers);
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException, BusinessException {
        Object res = super.decode(response, type);
        // 处理异常, 统一成自定义异常, 转换统一异常结果, 有性能损耗
        if (ObjectUtils.isEmpty(res)) {
            throw new BusinessException(ResultCodeEnum.THIRD_ERROR);
        }
        ResponseResult<?> resp = JsonUtil.toBean(res, ResponseResult.class);
        if (ResultCodeEnum.OK.getCode() != resp.getCode()) {
            throw new BusinessException(resp.getCode(), resp.getMsg(), resp.getErrorName());
        }
        return res;
    }
}